/**
 * 产品修改js
 */
var comValidform = null;
var returnStatus = false;
var productInfoUpdate = {
	dataCache : null,
	introduceUE : null,
	product_descriptionUI: null,
	incomeUE : null,
	riskctrlUE : null,
	signflowUE:null,
	key : null,
	companyId:null,
	creditorPhoneNum:null,
    jjsId:'15',
    getSysParam:function () {
        var url = 'mgr/parameterCtrl/getParameter?name=JJS_ID';
        var cb =function (data) {
            if (data.resultCode == 200) {
                productInfoUpdate.jjsId = data.result.value01;
            }
        }
        sendApiNoLoad(url, null, cb, 'GET');
    },
	getCompanyResource : function() {
		var url = 'mgr/companyCtrl/list';
		var params = {
			'curPage' : 0,
			'pageSize' : 9999,
			'id' : null,
			'name' : null
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择发行方</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
							+ singleObj.name + '</option>';
				}
				$('select[name="issuerId"]').append(option);
			}
		};
		sendApiNoLoadSync(url, params, cb, 'POST');

	},
	getHCAddRateResource : function() {
		var url = 'mgr/ProductInfoCtrl/getHCAddRateProdList';
		var params = {};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择加息产品</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
						+ singleObj.name + '</option>';
				}
				$('select[name="addRateProduct01"]').append(option);
				$('select[name="addRateProduct02"]').append(option);
			}
		};
		sendApiNoLoadSync(url, params, cb, 'GET');
	},
	
	getContractResource : function() {
		var url = 'mgr/agreementCtrl/list';
		var params = {
			'curPage' : 0,
			'pageSize' : 9999,
			'id' : null,
			'name' : null
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
							+ singleObj.name + "--" + singleObj.id + '</option>';
				}
				$('.agreements').append(option);
				//初始化下拉多选框
                $(".agreements").SumoSelect({
                    csvDispCount: 5,
                    captionFormat: '{0} 个被选中'
                });

                $(".agreements").change(function(){
                	var selecteds=$(".agreements option:selected").length;
                	if(selecteds==0){
                		$("#contractId").val("");
					}else{
                        $("#contractId").val("1");
					}

				})
			}
		};
		sendApiNoLoadSync(url, params, cb, 'POST');

	},
	
	getProParResource : function() {
		var url = 'mgr/ProductInfoCtrl/getParProdInfoList';
		var params = {
			'prodTopType':2
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择产品父标</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
							+ singleObj.name + '</option>';
				}
				$('select[name="parId"]').append(option);
			}
		};
		sendApiNoLoadSync(url, params, cb, 'POST');

	},
	startEvent : function() {
		$("#recordTab ul").idTabs();
		productInfoUpdate.introduceUE = UE.getEditor('introduce', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		productInfoUpdate.product_descriptionUI = UE.getEditor('productDescription', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		productInfoUpdate.incomeUE = UE.getEditor('income', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		productInfoUpdate.riskctrlUE = UE.getEditor('riskctrl', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		productInfoUpdate.signflowUE = UE.getEditor('signflow', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});

		productInfoUpdate.showInfoById();

		// 控制贴息选择
		$('.com-addForm select[name="discount"]').change(function() {
			var selVal = $(this).val();
			if (selVal == 1) {
				$('#txTr').css('display', '');
				$("input[name='discountRate']").attr('type', 'text');
				$("input[name='discountRate']").attr('ignore', '');
				$("input[name='discountEndDate']").attr('type', 'text');
				$("input[name='discountEndDate']").attr('ignore', '');
			} else {
				$('#txTr').css('display', 'none');
				$("input[name='discountRate']").attr('type', 'hidden');
				$("input[name='discountRate']").attr('ignore', 'ignore');
				$("input[name='discountRate']").val(null);
				$("input[name='discountEndDate']").val(null);
				$("input[name='discountEndDate']").attr('type', 'hidden');
				$("input[name='discountEndDate']").attr('ignore', 'ignore');
			}
		});
		
		// 控制产品计息时间和回本付息时间
		$('.com-addForm select[name="startDiv"]').change(function() {
			var selVal = $(this).val();
			if (selVal == 1) {
				//	alert("startDiv == 1");
				$("input[name='proDividStartDate']").attr('ignore', '');
				$("input[name='proDividendDate']").attr('ignore', '');
			} else {
				//alert("startDiv == 0");
				$("input[name='proDividStartDate']").attr('ignore', 'ignore');
				$("input[name='proDividendDate']").attr('ignore', 'ignore');
			}
		});

		//选择发行方时，如果是贵州场外，挂牌号不能为空
        $('.com-addForm select[name="issuerId"]').change(function () {
        	if(checkContain(productInfoUpdate.jjsId,$(this).val()) && $('#com-addForm input[name="listingNumber"]').val() == ""){
                $('#com-addForm input[name="listingNumberHidden"]').val("");
                $('#com-addForm input[name="licenseNumberHidden"]').val("");
			}else {
                $('#com-addForm input[name="listingNumberHidden"]').val("1");
                $('#com-addForm input[name="licenseNumberHidden"]').val("1");
			}
        });
        $('#com-addForm input[name="listingNumber"]').blur(function () {
            if(checkContain(productInfoUpdate.jjsId,$('.com-addForm select[name="issuerId"]').val()) && $(this).val() == ""){
                $('#com-addForm input[name="listingNumberHidden"]').val("");
            }else {
                $('#com-addForm input[name="listingNumberHidden"]').val("1");
            }
        });

        $('#com-addForm input[name="licenseNumber"]').blur(function () {
            if(checkContain(productInfoUpdate.jjsId,$('.com-addForm select[name="issuerId"]').val()) && $(this).val() == ""){
                $('#com-addForm input[name="licenseNumberHidden"]').val("");
            }else {
                $('#com-addForm input[name="licenseNumberHidden"]').val("1");
            }
        });
		
		comValidform = $(".com-addForm").Validform(
				{
					
					datatype : {
						"m0-2" : /^[0-9]+(.[0-9]{1,2})?$/
					},
					tiptype : 2,
					tipSweep : true,
					beforeSubmit : function(curform) {
						var url = 'mgr/ProductInfoCtrl/updateProductInfo';
						var params = jsUtils.serializeJson($('.com-addForm'));
						var introduce = productInfoUpdate.introduceUE
								.getContent();
						params.introduce = introduce;
						var income = productInfoUpdate.incomeUE.getContent();
						params.income = income;
						var riskctrl = productInfoUpdate.riskctrlUE
								.getContent();
						params.riskctrl = riskctrl;

						var product_description = productInfoUpdate.product_descriptionUI.getContent();
						params.productDescription = product_description;
						
						//如何签约l
						var signflow = productInfoUpdate.signflowUE
						.getContent();
						params.signflow = signflow;
						if (params.discount != 1) {
							delete params.discountDate,
							delete params.discountBeginDate;
							delete params.discountEndDate;
							delete params.discountRate;
						}
						
						if(params.proDividendDate == null || params.proDividendDate == ''){
							delete params.proDividendDate;
						}
						
						
						if(params.proDividStartDate == null || params.proDividStartDate == ''){
							delete params.proDividStartDate;
						}

						if(productInfoUpdate.creditorPhoneNum != null){
							params.creditorPhoneNum = productInfoUpdate.creditorPhoneNum;
						}

						if(params.buyChannel == 2 && params.creditorPhoneNum == null){
							alert("募集账号没有填写，填写后再提交");
							return false;
						}

						if(params.saleType == 4 && (params.addRate == null || params.addRate == '')){
							alert("额外收益类产品必须填写产品额外收益，填写后再提交");
							return false;
						}

                        if(parseInt(params.subscriptionOrigin) < parseInt(params.minAppendAccount)) {
                            alert("认购起点必须大于或等于最低追加金额");
                            return false;
                        }
                        if((params.subscriptionOrigin) % (params.minAppendAccount) != 0) {
                            alert("认购起点必须能整除最低追加金额");
                            return false;
                        }

						/*把选择的合同转成数组传到后台（修重BUG：插件如果选择单个结果不是数组，多个又是数组）*/
                        var agreements = new Array();
                        $(".agreements option:selected").each(function(){
                            agreements.push($(this).val())
                        })
                        params.agreements = agreements;

                        console.log(params);

						var cb = function(data) {
							alert(data.msg);
							// 成功返回
							if (data.resultCode == 200) {
								localStorage.removeItem(productInfoUpdate.key);
								var singleObj = data.result;

								localStorage.setItem(singleObj.id
										+ "_ProductType02_Key", JSON
										.stringify(singleObj));
								// 关闭窗口并刷新数据
								returnStatus = true;
							}
						};
						sendApiNoLoadSync(url, params, cb, 'POST');
						return false;
					}
				});
	},

	showInfoById : function() {
		
		var id = art.dialog.data('updId');
		productInfoUpdate.key = id + "_ProductType02_Key";

		var ret = eval('(' + localStorage.getItem(productInfoUpdate.key) + ')');
		 
		 
		for ( var i in ret) {
			var text = ret[i];
			if (i == 'establishDate' || i == 'onlineDate' || i == 'endDate'
					|| i == 'releasesDate' || i == 'balanceDate'
					|| i == 'discountDate'
					|| i == 'raiseBeginDate' || i == 'raiseEndDate'
					|| i == 'discountEndDate' 
					|| i == 'proDividStartDate'|| i == 'proDividendDate') {
				text = text == null ? '' : (new Date(text))
						.format('yyyy-MM-dd');
			} else if (i=='buyType'||i == 'isTest' ||i == 'issuerId' || i == 'prodType' || i == 'publishType'
					|| i == 'parId' || i == 'divStartType'
					|| i == 'riskLevel' || i == 'currency' || i == 'isOversea'
					|| i == 'discount'||i=='buyChannel'
					||i=='useCard'||i=='autStartDiv' ||i=='startDiv'
					||i=='addRateProduct01'||i=='addRateProduct02'
					||i=='saleType'||i=='limitNum'||i=='isParent'||i=='directional' || i=='creditorType'){

				if (i == 'discount' && text == 1) {
					$('#txTr').css('display', '');
					$("input[name='discountRate']").attr('ignore', '');
					$("input[name='discountEndDate']").attr('ignore', '');
				}

				$('#com-addForm select[name="' + i + '"]').val(text);
				continue;
			} else if (i == 'claimRecommendInfo' || i == 'creditAssignmentInfo'
					|| i == 'paymentSource' || i == 'remark' || i == 'fundUse'
					|| i == 'incomeDisType' || i == 'salePoint'
					|| i == 'commission') {
				$('#com-addForm textarea[name="' + i + '"]').val(text);
				continue;
		  
			}else if(i == 'clearDate'){
                text = text == null ? '' : (new Date(text)).format('yyyy-MM-dd hh:mm:ss');
			}else if(i == 'agreements'){ //合同下拉多选框
				$.each(text,function(index,value){
                    $('select.agreements')[0].sumo.selectItem(value.contractId+"");
                    $("#contractId").val("1");
				})

			}
			$('#com-addForm input[name="' + i + '"]').val(text);
		}
		if (ret.introduceTxt != null) {
			productInfoUpdate.introduceUE.ready(function() {
				productInfoUpdate.introduceUE.setContent(ret.introduceTxt);
			});
		}
		if (ret.incomeTxt != null) {
			productInfoUpdate.incomeUE.ready(function() {
				productInfoUpdate.incomeUE.setContent(ret.incomeTxt);
			});
		}
		if (ret.claimRecommendInfo != null) {
			productInfoUpdate.product_descriptionUI.ready(function() {
				productInfoUpdate.product_descriptionUI.setContent(ret.claimRecommendInfo);
			});
		}
		if (ret.riskctrlTxt != null) {
			productInfoUpdate.riskctrlUE.ready(function() {
				productInfoUpdate.riskctrlUE.setContent(ret.riskctrlTxt);
			});
		}
		if (ret.signflowTxt != null) {
			productInfoUpdate.signflowUE.ready(function() {
				productInfoUpdate.signflowUE.setContent(ret.signflowTxt);
			});
		}
		if(ret.creditorPhoneNum != null && ret.creditorPhoneNum!='' && ret.creditorPhoneNum.length == 11) {
			$("input[name=creditorPhoneNum]").attr("readonly","readonly");
			$("input[name=creditorPhoneNum]").attr("disabled","disabled");
			productInfoUpdate.creditorPhoneNum = ret.creditorPhoneNum;
		}

		if(ret.divStartType != null && ret.divStartType!=''){
			$("input[name=divStartType]").attr("readonly","readonly");
			$("input[name=divStartType]").attr("disabled","disabled");
		}
		if(ret.startDiv != null && ret.startDiv!=''){
			$("input[name=startDiv]").attr("readonly","readonly");
			$("input[name=startDiv]").attr("disabled","disabled");
		}
	},

	init : function() {
        productInfoUpdate.getSysParam();
		productInfoUpdate.getCompanyResource();
		productInfoUpdate.getContractResource();
		productInfoUpdate.getProParResource();
		productInfoUpdate.getHCAddRateResource();
		productInfoUpdate.startEvent();
		
		
	}
}
$(document).ready(function() {
	productInfoUpdate.init();
});
function submitForm() {
	comValidform.submitForm();
	return returnStatus;
}

/**
 * 检查value有没有包含key值
 * @param value
 * @param key
 */
function checkContain (value,key) {
    var array = value.split(",");
    var result = false;
    array.forEach(function (val) {
        if(val == key){
            result = true;
        }
    })

    return result;
}